package ThreadDemo;

/*
 * Author: JacksonCoder
 * FileName: ThreadAlter
 * Version: 1.0.0
 * Date: 2025/5/14
 */

public class ThreadAlter {
    private final Object lock = new Object();
    private boolean pingTurn = true;

    public void ping() throws InterruptedException{
        synchronized(lock){
            while(!pingTurn){
                lock.wait();
            }
            System.out.println("Ping");
            pingTurn = false;
            lock.notify();
        }
    }

    public void pong() throws InterruptedException{
        synchronized (lock){
            while(pingTurn){
                lock.wait();
            }
            System.out.println("Pong");
            pingTurn = true;
            lock.notify();
        }
    }

    public static void main(String[] args) {
        ThreadAlter game = new ThreadAlter();

        Thread t1 = new Thread(() ->{
            try{
                for(int i = 0; i < 10; i++){
                    game.ping();
                }
            }catch (InterruptedException e){
                Thread.currentThread().interrupt();
            }
        });

        Thread t2 = new Thread(() -> {
            try{
                for(int i = 0; i < 10; i++){
                    game.pong();
                }
            }catch (InterruptedException e){
                Thread.currentThread().interrupt();
            }
        });

        t1.start();
        t2.start();
    }

}
